package org.benjamin.lending.trusteeship.sumapay;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.entity.*;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * <p>本息到账报文方式(普通项目、协议投资项目)</p>
 */
@Component("sumpayReturnPrincipalInterestOperation")
public class ReturnPrincipalInterestOperation extends SumapayAbstractOperation {

    private final Logger logger = LogManager.getLogger();

    @Override
    protected void processRequest(Map<String, Object> requestMap, MemberInfo memberInfo, BorrowInfo borrowInfo, Map<String, Object> parameterMap) {
        BigDecimal sum = new BigDecimal(parameterMap.get("sum").toString());
        List<RepayDetail> repayDetailList = (List<RepayDetail>) parameterMap.get("RepayDetails");
        requestMap.put("projectCode", borrowInfo.getNo());
        requestMap.put("sum", sum);
        requestMap.put("payType", 2);
        List<Subledger> subledgerList = new ArrayList<Subledger>();
        for (RepayDetail repayDetail : repayDetailList) {
            String roleCode = this.getUserIdIdentity(repayDetail.getMemberInfo().getUsername());
            BigDecimal amount = repayDetail.getCapital().add(repayDetail.getInterest());
            subledgerList.add(new Subledger(0, roleCode, 0, amount));
        }
        try {
            requestMap.put(this.SUBLEDGER_LIST, this.objectMapper.writeValueAsString(subledgerList));
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(), e);
            throw new IllegalArgumentException("分账列表解析出现异常");
        }
    }

    @Override
    protected String signatureRequest(Map<String, Object> requestMap) {
        String[] keys = {"requestId", "merchantCode", "projectCode", "sum", "payType", this.SUBLEDGER_LIST,
                "noticeUlr", "mainAccountType", "mainAccountCode"};
        String[] temp = this.buildSignature(requestMap, keys);
        requestMap.put(this.SIGNATURE, temp[1]);
        return temp[0];
    }

    @Override
    protected void afterRequest(Map<String, Object> parameterMap, MemberInfo memberInfo, BorrowInfo borrowInfo, TrusteeshipRequest trusteeshipRequest) {
        trusteeshipRequest.setType(TrusteeshipType.ReturnPrincipalInterest);
    }

    @Override
    protected String[] signatureResponse(Map<String, Object> responseMap) {
        return new String[0];
    }
}
